package br.com.me.ceap.down;

import br.com.me.ceap.BaseMojo;
import br.com.me.ceap.MECEAPUtils;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * Created by Bruno Mendonça with IntelliJ IDEA.
 * User: brunol
 * Date: 31/10/11
 * Time: 15:04
 */
/**
 * Goal which download BPMN Process and put them into resource directory
 *
 * @goal downloadBPMNFiles
 * @requiresProject
 */
public class DownloadBPMNFilesMojo extends BaseMojo {
// ------------------------------ FIELDS ------------------------------

    /**
     * Directory for BPMN files
     *
     * @parameter default-value="${basedir}/src/main/resources/bpmn"
     * @required
     */
    private File projectBpmnDirectory;
    /**
     * Overwrite exiting BPMN Process File
     *
     * @parameter default-value="false"
     */
    private boolean overwriteExitingProcessFiles;

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface Mojo ---------------------

    private void fixFileExists(String fileName) {
        File file = new File(fileName);
        if (!file.exists())
            return;

        int countFile = 1;
        File newFile;
        do {
            String newBackupFileName = fileName + ".bak" + countFile;
            newFile = new File(newBackupFileName);
            countFile++;
        } while (newFile.exists());

        file.renameTo(newFile);
        this.getLog().info("Created backup " + newFile.getName());
    }

    public void execute() throws MojoExecutionException, MojoFailureException {
        this.getLog().debug("Preparing to download the customRoot process jar");
        WebClient webClient = MECEAPUtils.forDownloadBPMNFilesJAR(this);

        this.getLog().info("Downloading CustomRoot process jar file");
        Attachment attachment = webClient.get(Attachment.class);

        this.getLog().debug("Downloaded CustomRoot process jar file");

        if (!projectBpmnDirectory.exists()) {
            this.getLog().debug("Destiny directory doesn't exist. Creating " + projectBpmnDirectory);
            if (!projectBpmnDirectory.mkdirs())
                this.getLog().error("Error creating directory " + projectBpmnDirectory);
        }


        try {
            JarInputStream jarInputStream = new JarInputStream(attachment.getDataHandler().getInputStream());

            boolean hasWrote = false;

            JarEntry jarEntry;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                if (!jarEntry.getName().endsWith(".bpmn"))
                    continue;

                String bpmnFileName = projectBpmnDirectory + File.separator + jarEntry.getName();

                if (!overwriteExitingProcessFiles)
                    fixFileExists(bpmnFileName);

                FileOutputStream fileOutputStream = new FileOutputStream(bpmnFileName);
                IOUtils.copy(jarInputStream, fileOutputStream);
                fileOutputStream.close();

                this.getLog().info("Wrote " + bpmnFileName);
                hasWrote = true;
            }

            if (!hasWrote)
                this.getLog().info("There are no process on CustomRoot");
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
}
